import db from '../../utils/dbconf';
import makeres from '../../utils/res';
import { TargetDataNoneError } from '../../utils/classModal';
import { relactionTool } from './relactionTool';

export const TABLE_NAME = 'MJ_GROUP';

export const groupcrud = {
	getlist: async ({ query }, res) => {
		const { u_id } = res.locals;
		const { page = 1, size = 10, name = '', group_id } = query;
		const { count: total, data: list } = await db
			.table(TABLE_NAME)
			.where({ name: ['LIKE', `%${name}%`], u_id })
			.page(page, size)
			.countSelect();
		return res.send(makeres.success({ total, list }));
	},
	getdetail: async ({ params: { id } }, res) => {
		const { u_id } = res.locals;
		const item = await db.table(TABLE_NAME).where({ id, u_id }).find();
		const cards = await relactionTool.getbygroup(id);
		return res.send(makeres.success(Object.assign(item, { cards })));
	},
	add: async ({ body: data }, res) => {
		const { u_id } = res.locals;
		const id = await db.table(TABLE_NAME).add({ ...data, u_id });
		return res.send(makeres.success({ id }));
	},
	change: async ({ params: { id }, body: data }, res) => {
		const { u_id } = res.locals;
		const ok = await db.table(TABLE_NAME).where({ id, u_id }).update(data);
		if (!ok) throw new TargetDataNoneError();
		return res.send(makeres.putsuccess());
	},
	delete: async ({ params: { id } }, res) => {
		const { u_id } = res.locals;
		const ok = await db.table(TABLE_NAME).where({ id, u_id }).delete();
		if (!ok) throw new TargetDataNoneError();
		return res.send(makeres.deletesuccess());
	},
};
